package com.gitee.neuray.security.par.parworkinfo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.gitee.neuray.security.admin.dto.AdminOrgDto;
import com.gitee.neuray.security.admin.dto.StaffDto;
import com.gitee.neuray.security.common.msg.ObjectRestResponse;
import com.gitee.neuray.security.common.msg.TableResultResponse;
import com.gitee.neuray.security.common.rest.BaseController;
import com.gitee.neuray.security.common.util.Query;
import com.gitee.neuray.security.common.util.UUIDUtils;
import com.gitee.neuray.security.par.parworkclock.biz.ParworkclockBiz;
import com.gitee.neuray.security.par.parworkclock.vo.ParworkclockVo;
import com.gitee.neuray.security.par.parworkinfo.vo.ParworkinfoVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import com.gitee.neuray.security.par.parworkinfo.biz.ParworkinfoBiz;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 部门工作派发代码生成
 *
 * @author dev
 * @email ${email}
 * @date 2020-08-24 14:19:26
 */
@RestController
@RequestMapping("parworkinfo")
public class ParworkinfoController extends BaseController<ParworkinfoBiz,ParworkinfoVo> {
    @Autowired
    private ParworkinfoBiz parworkinfoBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ParworkclockBiz parworkclockBiz;

    /**
    * 分页获取列表
    * @param params
    * @return
    */
    @RequestMapping(value = "queryPage" ,method = RequestMethod.GET)
    public TableResultResponse queryPage(@RequestParam Map<String,Object> params){
        //查询列表数据
        Query query = new Query(params);
        ParworkinfoVo vo = null;
        TableResultResponse page = parworkinfoBiz.page(query);
        for (int i = 0; i < page.getResult().getData().size(); i++) {
            vo = (ParworkinfoVo) page.getResult().getData().get(i);
            //执行人回显
            //判断执行人是单位还是个人
            if (vo.getZxrlb() != null && vo.getZxr() != null) {
                if (vo.getZxrlb().equals("1")){
                    AdminOrgDto org  = parworkinfoBiz.findOrgById(vo.getZxr());
                    if (org != null) {
                        vo.setZxrstr(org.getOrgName());
                    }
                }else {
                    StaffDto staff = parworkinfoBiz.findStaffById(vo.getZxr());
                    if (staff != null) {
                        vo.setZxrstr(staff.getName());
                    }
                }
            }
            if (vo.getZrr() != null) {
                String[] strings = vo.getZrr().split(",");
                StringBuffer sb = new StringBuffer();
                //责任人id拆分
                for (int j = 0; j < strings.length; j++) {
                    StaffDto staff = parworkinfoBiz.findStaffById(strings[j]);
                    if (staff != null) {
                        if (j == strings.length-1){
                            sb.append(staff.getName());
                        }else {
                            sb.append(staff.getName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrrList(Arrays.asList(strings));
                //回显用字符串
                vo.setZrr(sb.toString());
            }
            if (vo.getZrdw() != null) {
                String[] strings1 = vo.getZrdw().split(",");
                StringBuffer buffer = new StringBuffer();
                //责任单位拆分
                for (int j = 0; j < strings1.length; j++) {
                    AdminOrgDto org = parworkinfoBiz.findOrgById(strings1[j]);
                    if (org != null) {
                        if (j == strings1.length-1){
                            buffer.append(org.getOrgName());
                        }else {
                            buffer.append(org.getOrgName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrdwList(Arrays.asList(strings1));
                //回显用字符串
                vo.setZrdw(buffer.toString());
            }
        }
        return page;
    }


    /**
     * 通过部门id查询本部门创建的的数据
     * 工作派发部门级
     * @param params
     * @return
     */
    @GetMapping(value = "listQueryByOrgId")
    public TableResultResponse listQueryByOrgId(@RequestParam Map<String,Object> params){
        //获取当前登陆人的部门id
        String orgCode = request.getHeader("orgCode");
        //return的数据
        TableResultResponse page = new TableResultResponse();
        //查询列表数据
        Query query = new Query(params);
        //放入当前登陆人的部门id
        query.put("id",orgCode);
        ParworkinfoVo vo = null;
        page = parworkinfoBiz.listQueryByOrgId(query);
        for (int i = 0; i < page.getResult().getData().size(); i++) {
            vo = (ParworkinfoVo) page.getResult().getData().get(i);
            //执行人回显
            //判断执行人是单位还是个人
            if (vo.getZxrlb() != null && vo.getZxr() != null) {
                if (vo.getZxrlb().equals("1")){
                    AdminOrgDto org  = parworkinfoBiz.findOrgById(vo.getZxr());
                    if (org != null) {
                        vo.setZxrstr(org.getOrgName());
                    }
                }else {
                    StaffDto staff = parworkinfoBiz.findStaffById(vo.getZxr());
                    if (staff != null) {
                        vo.setZxrstr(staff.getName());
                    }
                }
            }
            if (vo.getZrr() != null) {
                String[] strings = vo.getZrr().split(",");
                StringBuffer sb = new StringBuffer();
                //责任人id拆分
                for (int j = 0; j < strings.length; j++) {
                    StaffDto staff = parworkinfoBiz.findStaffById(strings[j]);
                    if (staff != null) {
                        if (j == strings.length-1){
                            sb.append(staff.getName());
                        }else {
                            sb.append(staff.getName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrrList(Arrays.asList(strings));
                //回显用字符串
                vo.setZrr(sb.toString());
            }
            if (vo.getZrdw() != null) {
                String[] strings1 = vo.getZrdw().split(",");
                StringBuffer buffer = new StringBuffer();
                //责任单位拆分
                for (int j = 0; j < strings1.length; j++) {
                    AdminOrgDto org = parworkinfoBiz.findOrgById(strings1[j]);
                    if (org != null) {
                        if (j == strings1.length-1){
                            buffer.append(org.getOrgName());
                        }else {
                            buffer.append(org.getOrgName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrdwList(Arrays.asList(strings1));
                //回显用字符串
                vo.setZrdw(buffer.toString());
            }
        }
        return page;
    }


    /**
     * 通过部门id查询执行人为本部门的数据
     * 工作跟踪部门级
     * @param params
     * @return
     */
    @GetMapping(value = "listWorkTrackingByOrgId")
    public TableResultResponse listWorkTrackingByOrgId(@RequestParam Map<String,Object> params){
        //获取当前登陆人的部门id
        String orgCode = request.getHeader("orgCode");
        //return的数据
        TableResultResponse page = new TableResultResponse();
        //查询列表数据
        Query query = new Query(params);
        //放入当前登陆人的部门id
        query.put("id",orgCode);
        ParworkinfoVo vo = null;
        page = parworkinfoBiz.listWorkTrackingByOrgId(query);
        for (int i = 0; i < page.getResult().getData().size(); i++) {
            vo = (ParworkinfoVo) page.getResult().getData().get(i);
            //执行人回显
            //判断执行人是单位还是个人
            if (vo.getZxrlb() != null && vo.getZxr() != null) {
                if (vo.getZxrlb().equals("1")){
                    AdminOrgDto org  = parworkinfoBiz.findOrgById(vo.getZxr());
                    if (org != null) {
                        vo.setZxrstr(org.getOrgName());
                    }
                }else {
                    StaffDto staff = parworkinfoBiz.findStaffById(vo.getZxr());
                    if (staff != null) {
                        vo.setZxrstr(staff.getName());
                    }
                }
            }
            if (vo.getZrr() != null) {
                String[] strings = vo.getZrr().split(",");
                StringBuffer sb = new StringBuffer();
                //责任人id拆分
                for (int j = 0; j < strings.length; j++) {
                    StaffDto staff = parworkinfoBiz.findStaffById(strings[j]);
                    if (staff != null) {
                        if (j == strings.length-1){
                            sb.append(staff.getName());
                        }else {
                            sb.append(staff.getName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrrList(Arrays.asList(strings));
                //回显用字符串
                vo.setZrr(sb.toString());
            }
            if (vo.getZrdw() != null) {
                String[] strings1 = vo.getZrdw().split(",");
                StringBuffer buffer = new StringBuffer();
                //责任单位拆分
                for (int j = 0; j < strings1.length; j++) {
                    AdminOrgDto org = parworkinfoBiz.findOrgById(strings1[j]);
                    if (org != null) {
                        if (j == strings1.length-1){
                            buffer.append(org.getOrgName());
                        }else {
                            buffer.append(org.getOrgName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrdwList(Arrays.asList(strings1));
                //回显用字符串
                vo.setZrdw(buffer.toString());
            }
        }
        return page;
    }




    /**
     * 根据当前登陆人的id获取数据
     * @param params
     * @return
     */
    @GetMapping(value = "listQueryByStaffId")
    public TableResultResponse listQueryByStaffId(@RequestParam Map<String,Object> params){
        //获取当前登陆人id
        String header = request.getHeader("userId");
        //查询列表数据
        Query query = new Query(params);
        //放入当前登陆人id
        query.put("id",header);
        ParworkinfoVo vo = null;
        TableResultResponse page = parworkinfoBiz.listQueryByStaffId(query);
        for (int i = 0; i < page.getResult().getData().size(); i++) {
            vo = (ParworkinfoVo) page.getResult().getData().get(i);
            //执行人回显
            //判断执行人是单位还是个人
            if (vo.getZxrlb() != null && vo.getZxr() != null) {
                if (vo.getZxrlb().equals("1")){
                    AdminOrgDto org  = parworkinfoBiz.findOrgById(vo.getZxr());
                    if (org != null) {
                        vo.setZxrstr(org.getOrgName());
                    }
                }else {
                    StaffDto staff = parworkinfoBiz.findStaffById(vo.getZxr());
                    if (staff != null) {
                        vo.setZxrstr(staff.getName());
                    }
                }
            }
            if (vo.getZrr() != null) {
                String[] strings = vo.getZrr().split(",");
                StringBuffer sb = new StringBuffer();
                //责任人id拆分
                for (int j = 0; j < strings.length; j++) {
                    StaffDto staff = parworkinfoBiz.findStaffById(strings[j]);
                    if (staff != null) {
                        if (j == strings.length-1){
                            sb.append(staff.getName());
                        }else {
                            sb.append(staff.getName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrrList(Arrays.asList(strings));
                //回显用字符串
                vo.setZrr(sb.toString());
            }
            if (vo.getZrdw() != null) {
                String[] strings1 = vo.getZrdw().split(",");
                StringBuffer buffer = new StringBuffer();
                //责任单位拆分
                for (int j = 0; j < strings1.length; j++) {
                    AdminOrgDto org = parworkinfoBiz.findOrgById(strings1[j]);
                    if (org != null) {
                        if (j == strings1.length-1){
                            buffer.append(org.getOrgName());
                        }else {
                            buffer.append(org.getOrgName()).append(",");
                        }
                    }
                }
                //id数组
                vo.setZrdwList(Arrays.asList(strings1));
                //回显用字符串
                vo.setZrdw(buffer.toString());
            }
        }
        return page;
    }


    /**
     * 根据部门id查询部门下所有人
     * @param params
     * @return
     */
    @GetMapping(value = "getStaffInfoByOrgId")
    public ObjectRestResponse getStaffInfoByOrgId(@RequestParam Map<String,Object> params){
        ObjectRestResponse response = new ObjectRestResponse();
        response.setResult(parworkinfoBiz.findStaffByOrgId(params.get("id").toString()));
        return response;
    }


    /**
     * 根据人员id查询当前人员部门
     * @return
     */
    @GetMapping(value = "getOrgInfoByStaffId")
    public ObjectRestResponse getOrgInfoByStaffId(@RequestParam Map<String,Object> params){
        StaffDto staff = parworkinfoBiz.findStaffById(params.get("id").toString());
        AdminOrgDto org = parworkinfoBiz.findOrgById(staff.getDeptCode());
        ObjectRestResponse response = new ObjectRestResponse();
        response.setResult(org);
        return response;
    }


    /**
     * 插入数据
     * @param entity
     */
    //@PostMapping(value = "insert")
    @RequestMapping(value = "insert" ,method = RequestMethod.POST)
    public ObjectRestResponse insert(@RequestBody ParworkinfoVo entity) throws Exception {
        String id = UUIDUtils.generateShortUuid();
        entity.setId(id);
        StringBuffer sb = new StringBuffer();
        if (entity.getZrdwList() != null) {
            //存放责任单位以','分割
            for (int i = 0; i < entity.getZrdwList().size(); i++) {
                if ( i == entity.getZrdwList().size()-1){
                    sb.append(entity.getZrdwList().get(i));
                }else {
                    sb.append(entity.getZrdwList().get(i)).append(",");
                }
            }
            entity.setZrdw(sb.toString());
        }
        sb = new StringBuffer();
        if (entity.getZrrList() != null) {
            //存放责任人以','分割
            for (int i = 0; i < entity.getZrrList().size(); i++) {
                if ( i == entity.getZrrList().size()-1){
                    sb.append(entity.getZrrList().get(i));
                }else {
                    sb.append(entity.getZrrList().get(i)).append(",");
                }
            }
            entity.setZrr(sb.toString());
        }
        parworkinfoBiz.insertSelective(entity);
        return new ObjectRestResponse().rel(true);
    }

    /**
     * 更新数据
     * @param entity
     */
    @PostMapping(value = "update")
    public ObjectRestResponse updatePar(@RequestBody ParworkinfoVo entity){
        StringBuffer sb = new StringBuffer();
        if (entity.getZrdwList() != null) {
            for (int i = 0; i < entity.getZrdwList().size(); i++) {
                if ( i == entity.getZrdwList().size()-1){
                    sb.append(entity.getZrdwList().get(i));
                }else {
                    sb.append(entity.getZrdwList().get(i)).append(",");
                }
            }
            entity.setZrdw(sb.toString());
        }
        sb = new StringBuffer();
        if (entity.getZrrList() != null) {
            for (int i = 0; i < entity.getZrrList().size(); i++) {
                if ( i == entity.getZrrList().size()-1){
                    sb.append(entity.getZrrList().get(i));
                }else {
                    sb.append(entity.getZrrList().get(i)).append(",");
                }
            }
            entity.setZrr(sb.toString());
        }
        parworkinfoBiz.updateById(entity);
        return new ObjectRestResponse().rel(true);
    }

    /**
     * 修改派发状态
     * @param params
     * @return
     */
    @PostMapping(value = "updateDistributeStatus")
    public ObjectRestResponse updateDistributeStatus(@RequestParam Map<String,Object> params){
        Query query = new Query(params);
        parworkinfoBiz.updateDistributeStatus(query);
        return new ObjectRestResponse().rel(true);
    }


    /**
     * 导入数据
     * @param multipartFile
     * @return
     */
    @PostMapping(value = "importFile")
    public ObjectRestResponse importFile (@RequestParam("file") MultipartFile multipartFile) {
        ObjectRestResponse response = new ObjectRestResponse();
        try {
            //读取excle数据
            List<Map<String, Object>> dataList = readExcleData(multipartFile.getInputStream());
            if (dataList != null){
                for (int i = 0; i < dataList.size(); i++) {
                    ParworkinfoVo vo = new ParworkinfoVo();
                    Map<String, Object> map = dataList.get(i);
                    //判断执行人类别
                    if ("单位".equals(map.get("col1"))){
                        AdminOrgDto col0 = parworkinfoBiz.findOrgByOrgName(map.get("col0").toString());
                        vo.setZxr(col0.getId());
                        vo.setZxrlb("1");
                    }else {
                        StaffDto col0 = parworkinfoBiz.findStaffByName(map.get("col0").toString());
                        vo.setZxr(col0.getId());
                        vo.setZxrlb("2");
                    }
                    //判断工作类别
                    if ("指令性工作".equals(map.get("col2"))){
                        vo.setGzlb("1");
                    }else if ("目标任务问题清单".equals(map.get("col2"))){
                        vo.setGzlb("2");
                    }else {
                        vo.setGzlb("3");
                    }
                    //判断清单类型
                    if ("问题类型".equals(map.get("col3"))){
                        vo.setQdlx("1");
                    }else if ("任务类型".equals(map.get("col3"))){
                        vo.setQdlx("2");
                    }else if ("工作类型".equals(map.get("col3"))){
                        vo.setQdlx("3");
                    }
                    //插入工作内容
                    vo.setGznr(map.get("col4")==null?null:map.get("col4").toString());
                    //判断是否是周期性工作
                    if ("是".equals(map.get("col5"))){
                        vo.setSfszqxgz("1");
                    }else {
                        vo.setSfszqxgz("2");
                    }
                    //判断周期
                    if ("年".equals(map.get("col6"))){
                        vo.setZq("1");
                    }else if ("季度".equals(map.get("col6"))){
                        vo.setZq("2");
                    }else if ("月".equals(map.get("col6"))){
                        vo.setZq("31");
                    }else if ("周".equals(map.get("col6"))){
                        vo.setZq("4");
                    }else if ("日".equals(map.get("col6"))){
                        vo.setZq("5");
                    }else if ("自定义".equals(map.get("col6"))){
                        vo.setZq("6");
                    }
                    //插入自定义周期
                    vo.setZdyzq(map.get("col7")==null?null:map.get("col7").toString());
                    //插入开始时间
                    if (map.get("col8") != null){
                        Date date = DateUtil.parse(map.get("col8").toString());
                        vo.setKssj(date);
                    }
                    //插入结束时间
                    if (map.get("col9") != null){
                        Date date = DateUtil.parse(map.get("col9").toString());
                        vo.setJzsj(date);
                    }
                    //插入责任单位
                    if (map.get("col10") != null) {
                        String[] strings = map.get("col10").toString().split(",");
                        StringBuffer buffer = new StringBuffer();
                        for (int j = 0; j < strings.length; j++) {
                            AdminOrgDto org = parworkinfoBiz.findOrgByOrgName(strings[j]);
                            if (j == strings.length-1){
                                buffer.append(org.getId());
                            }else {
                                buffer.append(org.getId()).append(",");
                            }
                        }
                        vo.setZrdw(buffer.toString());
                    }
                    //插入责任人
                    if (map.get("col11") != null) {
                        String[] strings = map.get("col11").toString().split(",");
                        StringBuffer buffer = new StringBuffer();
                        for (int j = 0; j < strings.length; j++) {
                            StaffDto staff = parworkinfoBiz.findStaffByName(strings[j]);
                            if (j == strings.length-1){
                                buffer.append(staff.getId());
                            }else {
                                buffer.append(staff.getId()).append(",");
                            }
                        }
                        vo.setZrr(buffer.toString());
                    }
                    //插入质量要求
                    if (map.get("col12") != null) {
                        vo.setZlyq(map.get("col12").toString());
                    }
                    parworkinfoBiz.insertSelective(vo);
                }
            }
            response.setMessage("导入成功");
            response.rel(true);
        }catch (Exception e){
            e.printStackTrace();
            response.setMessage("导入失败，请使用模板导入");
            response.rel(false);
            return response;
        }
        return response;
    }

    /**
     * 读取excel数据
     * @param inputStream
     * @return
     */
    private List<Map<String, Object>> readExcleData(InputStream inputStream) {
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> readAll = reader.read();
        //去除excel中的第一行数据
        readAll.remove(0);
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 0; i < readAll.size(); i++) {
            if (null != readAll.get(i)) {
                Map<String, Object> hashMap = new HashMap<>();
                for (int j = 0; j < readAll.get(i).size(); j++) {
                    Object property = readAll.get(i).get(j);
                    hashMap.put("col"+j, property);
                }
                dataList.add(hashMap);
            } else {
                break;
            }
        }
        return dataList;
    }


    /**
     * 下载模板
     * @param response
     */
    @RequestMapping(value = "export", method = RequestMethod.GET)
    public void download(HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        String fileName = "工作模板";
        try {
            Resource resource = new ClassPathResource("template.xlsx");
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 更新数据并且插入打卡数据
     * @param params
     */
    @PostMapping(value = "updateParAndInsertWorkClock")
    public ObjectRestResponse updateParAndInsertWorkClock(@RequestParam Map<String,Object> params) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        SimpleDateFormat sdfs = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        //主表
        ParworkinfoVo parworkinfoVo = new ParworkinfoVo();
        parworkinfoVo.setWcsj(sdf.parse(params.get("wcsj").toString()));
        parworkinfoVo.setGzzt("1");
        parworkinfoVo.setId(params.get("workinfoid").toString());
        if (params.get("yqyy") != null) {
            parworkinfoVo.setYqyy(params.get("yqyy").toString());
        }
        parworkinfoBiz.updateSelectiveById(parworkinfoVo);
        //子表
        ParworkclockVo parworkclockVo = new ParworkclockVo();
        parworkclockVo.setBz(params.get("bz").toString());
        parworkclockVo.setWorkInfoId(params.get("workinfoid").toString());
        parworkclockVo.setDksj(sdfs.parse(params.get("wcsj").toString()));
        parworkclockBiz.insertSelective(parworkclockVo);
        return new ObjectRestResponse().rel(true);
    }

    /**
     * 插入打卡数据
     *
     * @param parworkclockVo
     * @return
     */
    @PostMapping(value = "insertClock")
    public ObjectRestResponse insertClock(@RequestBody ParworkclockVo parworkclockVo) {
        parworkclockBiz.insertSelective(parworkclockVo);
        return new ObjectRestResponse().rel(true);
    }

    /**
     * 打卡列表
     * @param params
     * @return
     */
    @RequestMapping(value = "listClock", method = RequestMethod.GET)
    public TableResultResponse listClock(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        return parworkclockBiz.list(query);
    }







}
